# -*- coding: utf-8 -*-


import unittest2

from util.selenium import webdriver
from util.selenium.webdriver import ChromeOptions

import time

from util.selenium.webdriver.common.by import By
from util.selenium.webdriver.support import expected_conditions as EC


from base.BaseMethod import BM
from settings import chrome_driver_path, start_url, ResTypeMapping, TypeSqlMapping, res_base_sql, web_type
from util.g import g


class BasePage(unittest2.TestCase):

    def setUp(self):
        option = ChromeOptions()

        option.add_experimental_option('excludeSwitches', ['enable-automation'])

        self.driver = webdriver.Chrome(executable_path=chrome_driver_path, options=option)
        # self.driver = webdriver.Firefox()
        # self.driver = webdriver.Ie()

        self.driver.maximize_window()
        self.driver.implicitly_wait(15)

    def tearDown(self):
        time.sleep(5)
        self.driver.quit()


class Base():

    def __init__(self):
        option = ChromeOptions()

        option.add_experimental_option('excludeSwitches', ['enable-automation'])

        self.driver = webdriver.Chrome(executable_path=chrome_driver_path, options=option)

        self.driver.maximize_window()

    def open(self):
        self.driver.get(start_url)

        self.driver.implicitly_wait(15)


# TODO 附件上传方法 备份
    # # # # 上传按钮点击
    @staticmethod
    def click_upload_attach(btn_loc, driver=None, class_name="", _id=None):
        if not driver:
            raise NameError("driver is not defind. custom--")

        res_type = ResTypeMapping.get(class_name)
        sql_info = TypeSqlMapping.get(res_type)
        condition = sql_info.get("condition")
        sql = res_base_sql.format(table=sql_info.get("table"))
        if "{id}" in condition:
            sql += " " + condition.format(co_id=g.co_id, year=g.year, id=_id)
        else:
            sql += " " + condition.format(co_id=g.co_id, year=g.year)
        file_path = BM.get_file_path(sql=sql)
        if not file_path:
            g.logger.error("没有获取到附件目录")
            return
        # upload_loc = (By.CSS_SELECTOR, "#yyzzFile")
        download_loc = (By.CSS_SELECTOR, ".progress-button.uploadBtn")
        if BM.is_element_block(ele_loc=download_loc, driver=driver):
            g.logger.info("附件已上传 sql={sql}".format(sql=sql))
            return
        upload_loc = (By.CSS_SELECTOR, "#{file_id}".format(file_id=BM.get_file_id(driver=driver, ele_loc=btn_loc)))
        div_loc = (By.CSS_SELECTOR, "#uniform-yyzzFile")
        if BM.isElementExist(element=div_loc, driver=driver):
            BM.display_element(driver=driver, ele_loc=div_loc, display="block")
        BM.display_element(driver=driver, ele_loc=upload_loc, display="block")
        BM.input(driver=driver, ele_loc=upload_loc, keys=file_path)
        alert = EC.alert_is_present()(driver)
        if not alert:
            # g.logger.info("没有alert框弹出")
            return False
        text = alert.text
        g.logger.info("上传提示：{tishi} 上传sql={sql}".format(tishi=text, sql=sql))
        alert.accept()
        if BM.isElementExist(element=div_loc, driver=driver):
            BM.display_element(driver=driver, ele_loc=div_loc, display="none")
            time.sleep(1)

    @staticmethod
    def click_upload(btn_loc=(), tip_loc=(), download_loc=(), driver=None, class_name=""):
        res_type_dict = ResTypeMapping.get(class_name)
        res_type = None
        year = None
        if isinstance(res_type_dict, str):
            res_type = res_type_dict
        if tip_loc:
            BM.wait(driver=driver, ele_loc=tip_loc)
            tip = driver.find_element(*tip_loc).text
            for k, v in res_type_dict.items():
                if k in tip:
                    res_type = v
                    break
            if res_type is None:
                g.logger.error("附件未上传 或 网站提示改变： tip={tip}".format(tip=tip))
                return
            material_year = BM.get_year(tip_str=tip)
            if material_year:
                year = BM.get_year(tip_str=tip)

        rule_id = BM.get_rule_id(res_type=res_type, year=year if year else None)
        sql = res_base_sql.format(
            table="ent_res_pdf") + \
              " where co_id={co_id} and year={year} and web_type='{web_type}' and (res_type='{res_type}' or rule_id={rule_id})".format(
                  co_id=g.co_id, year=g.year, web_type=web_type, res_type=res_type, rule_id=rule_id)
        if year:
            sql += " and res_code={res_code}".format(res_code=year)
        file_path = BM.get_file_path(sql=sql)
        if not file_path:
            g.logger.error("没有获取到附件目录")
            return
        download_loc = (By.CSS_SELECTOR, ".progress-button.uploadBtn")
        if res_type == "hr":
            if BM.is_element_block(ele_loc=download_loc, driver=driver):
                g.logger.info("附件已上传 sql={sql}".format(sql=sql))
                return
        else:
            if res_type != "cooperation":
                btn_text = driver.find_element(*btn_loc).text
                # print(btn_text, btn_loc, file_path, res_type, tip)
                delete_loc = (btn_loc[0], btn_loc[1].replace(" a", " button"))
                # print(u"点击下载" in btn_text, BM.is_element_block(ele_loc=delete_loc, driver=driver), delete_loc)
                if u"点击下载" in btn_text and BM.is_element_block(ele_loc=delete_loc, driver=driver):
                    g.logger.info("附件已上传 sql={sql}".format(sql=sql))
                    return
        file_id = BM.get_file_id(driver=driver, ele_loc=btn_loc)
        if file_id is None:
            g.logger.info("附件已上传 sql={sql}".format(sql=sql))
            return
        upload_loc = (By.CSS_SELECTOR, "#{file_id}".format(file_id=file_id))
        div_loc = (By.CSS_SELECTOR, "#uniform-yyzzFile")
        if BM.isElementExist(element=div_loc, driver=driver):
            BM.display_element(driver=driver, ele_loc=div_loc, display="block")
        BM.display_element(driver=driver, ele_loc=upload_loc, display="block")
        BM.input(driver=driver, ele_loc=upload_loc, keys=file_path)
        BM.touch_method(driver=driver, select="#{}".format(file_id), method="onchange")
        alert = EC.alert_is_present()(driver)
        if not alert:
            # print("没有alert框弹出")
            return False
        text = alert.text
        # alert = Alert()
        alert.accept()
        if BM.isElementExist(element=div_loc, driver=driver):
            BM.display_element(driver=driver, ele_loc=div_loc, display="none")
            time.sleep(1)
